<?php

namespace app\common\taglib;

use think\template\TagLib;
use think\facade\Db;

class ZmCMS extends TagLib
{
    /**
     * 定义标签列表
     */
    protected $tags = array(
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'zhimeng' => array('attr' => 'table,cid,where,order,limit,id,page,sql,field,expired,cache', 'alias' => 'zhimeng', 'close' => 1), //闭合标签，默认为不闭合
        'read' => array('attr' => 'table,field,id', 'alias' => 'read', 'close' => 1, 'alias' => 'read'), //闭合标签，默认为不闭合
        'zminner' => array('attr' => 'table,cid,join_a,join_b,jointype,where,order,limit,id,page,field,cache', 'close' => 1), //闭合标签，默认为不闭合
        'ad' => array('attr' => 'alias,id', 'close' => 1), //闭合标签，默认为不闭合
    );

    /**
     * 循环读取列表
     */
    public function tagzhimeng($tag, $content)
    {
        $table = isset($tag['table']) ? $tag['table'] : false;
		if(!$table){ //如果没有设置表参数，直接返回内容 
			return $content;
		}
        $where = !empty($tag['where']) ? $tag['where'] : '';
        $cid = !empty($tag['cid']) ? $tag['cid'] : '';
        $order = !empty($tag['order']) ? $tag['order'] : '';
        $limit = !empty($tag['limit']) ? intval($tag['limit']) : '';
        $id = !empty($tag['id']) ? $tag['id'] : 'r';
        $key = !empty($tag['key']) ? $tag['key'] : 'i';
        $field = !empty($tag['field']) ? $tag['field'] : '';
        $cache = !empty($tag['cache']) ? $tag['cache'] : '';
        $page = !empty($tag['page']) ? $tag['page'] : '';
        $mod = !empty($tag['mod']) ? $tag['mod'] : '2';
        $parseStr = '<?php ' . "\r\n";
        $m = "m" . mt_rand(100000, 999999);
        $ret = 'ret' . mt_rand(100000, 999999);
        $parseStr .= '$whereCondition=array();'."\r\n";  //查询条件重置
        if (!empty($cid)) {
            $parseStr .= 'if(isset($cid)&&$cid!=0) { ' . "\r\n";
            $parseStr .= '$childCategoryID=getCategoryChildAll(' . $cid . ');' . "\r\n";
            $parseStr .= '$instr=implode(",",$childCategoryID);' . "\r\n";
            $parseStr .= '$whereCid[]=["catid","in",$instr];' . "\r\n";
            $parseStr .= ' }else { $whereCid=[]; }' . "\r\n";
        }
		
		if($where){
			$parseStr.='$whereCondition='.$where.';'."\r\n";	
		}
		if($cid){
			$parseStr.='$whereCondition=array_merge($whereCondition,$whereCid);'."\r\n";		
		}
		if($page){
			$parseStr.='$page=isset($page)?$page:1;'."\r\n";	
		}		
        $parseStr .= '$' . $ret . ' =\think\facade\Db::name("' . $table . '")';
		$parseStr.= '->where($whereCondition)';
        if ($field) {
            $parseStr .= '->field("' . $field . '")';
        }
        if ($limit && !$page) {
            $parseStr .= '->limit(0,' . $limit . ')';
        }
        if ($cache) {
            $parseStr .= '->cache(true,' . $cache . ')';
        }
        if ($order) {
            $parseStr .= '->order("' . $order . '")';
        }
        if ($page) {
            $parseStr.=" ->paginate(['list_rows' => ".$limit.", 'page' => ".$page."]);\r\n";
            $parseStr.='$page=$' . $ret . '->render();'; //分页配置
            $parseStr.='$count=$' . $ret . '->total();'; //总记录数
        } else {
            $parseStr .= '->select();' . "\r\n";//没有分页使用select
        }
        $parseStr .= 'if ($' . $ret . '){ $' . $key . '=0;' . "\r\n";
        $parseStr .= 'foreach($' . $ret . ' as $key=>$' . $id . ')';
        $parseStr .= '{ ++$' . $key . ';$mod = ($' . $key . ' % ' . $mod . ' );?>';
        $parseStr .= $content;
        $parseStr .= '<?php }}?>';
        return $parseStr;
    }
	
    /**
     * 读取单条信息
     */
    public function tagread($tag, $content)
    {
        $name = isset($tag['table']) ? $tag['table'] : die('Table is empty');
        $field = isset($tag['field']) ? $tag['field'] : '*';
        $id = isset($tag['id']) ? $tag['id'] : 0;
        if (!$id) {
            die("bad request");
        }
        $str = '<?php ' . "\r\n";
        $str .= '$fid=' . $id . ";\r\n";
        $str .= '$id=intval($fid)' . ";\r\n";
        $str .= '$data=\think\facade\Db::name(\'' . $name . '\')->field(\'' . $field . '\')->where("id",$id)->find();' . "\r\n"; //查询语句
        $str .= '$prevs=\think\facade\Db::name("' . $name . '")->field("' . $field . '")->where("id","<",$id)->find();' . "\r\n"; //上一条
        $str .= '$nexts=\think\facade\Db::name("' . $name . '")->field("' . $field . '")->where("id",">",$id)->find();' . "\r\n"; //下一条
        $click_str = "<script language='javascript' src='/api/click/view.html?id=" . $id . "&model=" . $name . "'></script>";
        $str .= '$click_show="' . $click_str . '";' . "\r\n"; //统计点击次数
        $str .= 'if($data){extract($data);}' . "\r\n";
        $str .= $content;
        $str .= '  ?>';
        return $str;
    }

    /**
     * 广告标签，读取广告
     */
    public function tagad($tag, $content)
    {
        $alias = isset($tag['alias']) ? $tag['alias'] : die('alias is empty');
        $id = isset($tag['id']) ? $tag['id'] : 'r';
        if (!$id) {
            die("bad request");
        }
        $str = '<?php ' . "\r\n";
        $str .= '$fields="a.*,b.alias";' . "\r\n";
        $str .= '$where_ad[]=["b.alias","=","' . $alias . '"];' . "\r\n";
        $str .= '$where_ad[]=["a.start_time","<=",time()];' . "\r\n";
        $str .= '$where_ad[]=["a.end_time",">=",time()];' . "\r\n";
        $str .= '$adLists=Db::name("ad")->alias("a")->field($fields)->where($where_ad)->join("ad_postion b","b.id=a.postion_id","LEFT")->order(["sort"=>"asc","id"=>"desc"])->select();';
        $str .= 'if ($adLists){ $indexKey=0;' . "\r\n";
        $str .= 'foreach($adLists as $key=>$' . $id . ')';
        $str .= '{ ++$indexKey;?>';
        $str .= $content;
        $str .= '<?php }}?>';
        return $str;
    }

}

